package com.zito.chat;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.comet4j.core.CometConnection;
import org.comet4j.core.event.ConnectEvent;
import org.comet4j.core.listener.ConnectListener;
import org.comet4j.core.util.JSONUtil;

import com.zito.chat.dto.JoinDTO;
import com.zito.chat.dto.UserDTO;
import com.zito.manager.InteractSession;



/**
 * 用于上线的监听类
 * 
 * @author wbh
 * @date Mon Aug 04 16:43:38 CST 2014
 */
public class OnLineListener extends ConnectListener {

	@Override
	public boolean handleEvent(ConnectEvent anEvent) {
		CometConnection conn = anEvent.getConn();
		HttpServletRequest request = conn.getRequest();
		String userName = InteractSession.get().getUserName(request);// 获取用户姓名
		JoinDTO dto = new JoinDTO(conn.getId(), userName); 
		AppStore.getInstance().put(conn.getId(), userName);
		anEvent.getTarget().sendToAll(Constant.APP_CHANNEL, dto);
		List<UserDTO> userList = new ArrayList<UserDTO>();
		Map<String, String> map = AppStore.getInstance().getMap();
		Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> entry = iter.next();
			String id = entry.getKey();
			String name = entry.getValue();
			userList.add(new UserDTO(id, name));
		}
		JSONUtil.convertToJson(userList);
		return true;
	}
}
